package com.wangmeng.book.job;

import com.wangmeng.book.dao.BaseDaoSupport;
import com.wangmeng.book.entity.BookDoc;
import com.wangmeng.book.updater.BookFromSina;
import com.wangmeng.book.updater.BookFromSohu;
import com.wangmeng.book.updater.BookFromTx;
import com.wangmeng.book.updater.BookFromWy;
import com.wangmeng.book.utils.ConstValueUtils;
import com.wangmeng.book.utils.SpringContextManager;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * User: 王猛
 * Date: 13-9-29
 * 内容更新任务
 */
public class ContentLoadJob implements Runnable {
    private static final Logger logger = Logger.getLogger(ContentLoadJob.class);

    public void run() {
        logger.info("内容下载检查开始");
        try {
            BaseDaoSupport daoSupport = SpringContextManager.getContext().getBean(BaseDaoSupport.class);
            List<BookDoc> bookList = daoSupport.listEntityByCondition(BookDoc.class, " and approveStatus = ? ", new Object[]{ConstValueUtils.APPROVE_RECEIVE});
            BookFromTx bft = new BookFromTx();
            BookFromSina bfs = new BookFromSina();
            BookFromWy bfw = new BookFromWy();
            BookFromSohu bfu = new BookFromSohu();
            for (BookDoc bd : bookList) {
                int sType = bd.getSourceType();
                int backCode = ConstValueUtils.CODE_EXCEPTION;
                switch (sType) {
                    case ConstValueUtils.SOURCE_TYPE_TX: {
                        backCode = bft.loadContent(bd);
                        break;
                    }
                    case ConstValueUtils.SOURCE_TYPE_SN: {
                        backCode = bfs.loadContent(bd);
                        break;
                    }
                    case ConstValueUtils.SOURCE_TYPE_WY: {
                        backCode = bfw.loadContent(bd);
                        break;
                    }
                    case ConstValueUtils.SOURCE_TYPE_SH: {
                        backCode = bfu.loadContent(bd);
                        break;
                    }
                }
                if (backCode == ConstValueUtils.CODE_SUCCESS) {
                    bd.setApproveStatus(ConstValueUtils.APPROVE_RECEIVE_SUCCESS);
                } else {
                    bd.setApproveStatus(ConstValueUtils.APPROVE_RECEIVE_FAIL);
                }
                daoSupport.saveEntity(bd);
            }
        } catch (Exception ex) {
            logger.error("内容下载检查异常", ex);
        } finally {
            logger.info("内容下载检查结束");
        }
    }
}
